<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="auto"
    class="product-form"
    status-icon
  >
    <el-form-item label="商品名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入商品名称" />
    </el-form-item>

    <el-form-item label="商品标题" prop="subName">
      <el-input v-model="formData.subName" placeholder="请输入商品标题" />
    </el-form-item>

    <el-form-item label="商品图片" prop="img">
      <div class="image-upload-group">
        <Tuku v-model="formData.img" />
        <Tuku v-model="formData.img1" />
        <Tuku v-model="formData.img2" />
      </div>
    </el-form-item>

    <el-form-item label="商品排序" prop="seq">
      <el-input-number
        v-model="formData.seq"
        :min="1"
        :max="10"
        placeholder="请选择排序"
      />
    </el-form-item>

    <el-form-item label="商品价格" prop="price">
      <el-input-number
        v-model="formData.price"
        :precision="2"
        :step="0.1"
        placeholder="请输入价格"
      />
    </el-form-item>

    <el-form-item label="父类目ID" prop="categoryId">
      <el-tree-select
        v-model="formData.categoryId"
        :data="categoryData"
        check-strictly
        :render-after-expand="false"
        class="category-select"
        placeholder="请选择类目"
      />
    </el-form-item>

    <el-form-item label="商品简介" prop="brief">
      <editors v-model="formData.brief" :height="100" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      <el-button @click="resetForm(formRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue"
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import Tuku from "@/components/Tuku.vue"
import Editors from "@/components/Editors.vue"
import { CategoryApi, ProductApi } from "@/api"

// 类型定义
interface FormData {
  id: number
  name: string
  subName: string
  img: string
  img1: string
  img2: string
  seq: number
  price: number
  brief: string
  categoryId: number
}

interface CategoryItem {
  id: number
  name: string
  parentId: number
  value?: number
  label?: string
  children?: CategoryItem[]
}

// 路由实例
const route = useRoute()
const router = useRouter()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<FormData>({
  id: 0,
  name: '',
  subName: '',
  img: '',
  img1: '',
  img2: '',
  seq: 1,
  price: 0,
  brief: '',
  categoryId: 0
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '商品名称为必填项', trigger: 'blur' },
    { min: 2, max: 15, message: '商品名称长度应在2-15个字符之间', trigger: 'blur' },
  ]
}

// 类目数据
const categoryData = ref([
  {
    value: 0,
    label: '一级目录',
  },
])

// 生命周期钩子
onMounted(() => {
  formData.id = Number(route.query.id)
  loadCategories()
  loadProductData()
})

// 加载类目数据
const loadCategories = async () => {
  try {
    const res = await CategoryApi.select.call()
    const formattedData = formatCategoryData(res)
    categoryData.value = formattedData
  } catch (error) {
    ElMessage.error('加载类目数据失败')
  }
}

// 格式化类目数据
const formatCategoryData = (data: CategoryItem[]) => {
  // 添加 value 和 label 字段
  data.forEach(item => {
    item.value = item.id
    item.label = item.name
  })

  // 构建树形结构
  return data.reduce((acc: CategoryItem[], curr: CategoryItem) => {
    curr.children = data.filter(item => item.parentId === curr.id)
    if (curr.parentId === 0) {
      acc.push(curr)
    }
    return acc
  }, [])
}

// 加载商品数据
const loadProductData = async () => {
  try {
    const res = await ProductApi.select.call({ id: formData.id })
    const product = res[0]
    
    // 处理基本信息
    formData.name = product.name
    formData.subName = product.subName
    formData.seq = product.seq
    formData.price = product.price
    formData.categoryId = product.categoryId
    formData.brief = product.brief

    // 处理图片信息
    const images = product.img.split(',')
    formData.img = images[0] || ''
    formData.img1 = images[1] || ''
    formData.img2 = images[2] || ''
  } catch (error) {
    ElMessage.error('加载商品数据失败')
  }
}

// 提交表单数据
const submitFormData = async () => {
  try {
    await ProductApi.update.call({
      id: formData.id,
      name: formData.name,
      subName: formData.subName,
      img: [formData.img, formData.img1, formData.img2].filter(Boolean).join(','),
      seq: formData.seq,
      price: formData.price,
      brief: formData.brief,
      categoryId: formData.categoryId
    })
    
    ElMessage.success("修改成功")
    router.push({ name: 'product-list' })
  } catch (error) {
    ElMessage.error("修改失败")
  }
}

// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  await formEl.validate((valid, fields) => {
    if (valid) {
      submitFormData()
    } else {
      console.error('表单验证失败:', fields)
    }
  })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.product-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.image-upload-group {
  display: flex;
  gap: 16px;
}

.category-select {
  width: 150px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-button) {
  padding: 12px 20px;
  border-radius: 4px;
}
</style>